// import { SUCCESS_CODE } from '@/utils/request';
import { UploadOutlined } from '@ant-design/icons';
import { ProForm } from '@ant-design/pro-components';
import type { UploadFile, UploadProps } from 'antd';
import { Button, message, Modal, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { RcFile } from 'antd/lib/upload';
import { useState } from 'react';
import { updateImage } from '../service';
import type { imageList } from '../types';
// import { judgeHas_exists, UpdateParkItem } from '../service';
// import type { imageList } from '../types';

interface configImageList {
  id: string;
  visible: boolean;
  unVisible: () => void;
  reloadFunc: () => void;
  Image: UploadFile[];
  Urls: string[];
}
const getBase64 = (file: RcFile): Promise<string> =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });

export default (props: configImageList) => {
  const { visible, unVisible, id, reloadFunc, Urls, Image } = props;
  console.log('Urls', Urls);
  console.log('Images', Image);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [fileList, setFileList] = useState<UploadFile[]>(Image);
  // const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [pictures, setpictures] = useState<string[]>(Urls);
  const [addUrl, setAddUrl] = useState<string[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  const onChange: UploadProps['onChange'] = async (info) => {
    console.log('info', info);

    if (info.file.status === 'done') {
      setpictures(pictures?.concat(info.file.response.data.url));
      setAddUrl(addUrl.concat(info.file.response.data.url));
      message.success(`${info.file.name} 加载成功`);
    } else if (info.file.status === 'removed') {
      setpictures(addUrl.concat(info.fileList?.map((v) => v.url).filter((v) => !!v) as string[]));
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 加载失败`);
    }
  };

  const handleCancel = () => setPreviewVisible(false);
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as RcFile);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewVisible(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };

  return (
    <div>
      <Modal
        onCancel={unVisible}
        centered
        visible={visible}
        title="配置车场图片(可添加0-9张图片)"
        destroyOnClose
        width={800}
        footer={null}
      >
        <ProForm
          submitter={{
            resetButtonProps: {
              style: {
                // 隐藏重置按钮
                display: 'none',
              },
            },
          }}
          onFinish={async () => {
            const values: imageList = {
              zoneId: id,
              urls: pictures,
            };

            const hide = message.loading('正在提交');
            try {
              const res = await updateImage(values);
              hide();
              if (res.code === 0) {
                message.success('添加成功');
                unVisible();
                reloadFunc();
                return true;
              }
              message.error(`添加失败！${res.message}`);
              return false;
            } catch (error) {
              hide();
              message.error('添加失败！未知的错误！');
              return false;
            }
          }}
        >
          <ProForm.Item
            name="picture"
            label="上传图片:"
            // rules={[{ required: true}]}
            style={{ width: 500, height: 400 }}
            font-size="larger"
          >
            <ImgCrop
              grid
              rotate
              aspect={375 / 144}
              quality={1}
              beforeCrop={(file: File): Promise<boolean> =>
                new Promise<boolean>((resolve, rejects) => {
                  const { name } = file;
                  // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
                  const nameRegExp = new RegExp('(.jpeg|.png|.jpg)$');
                  const isImage = nameRegExp.test(name);
                  const isLt512K = file.size / 1024 < 512;
                  if (!isImage) {
                    message.error({
                      content: '文件类型错误, 请上传一个图片文件,支持格式jp(e)g或png',
                      key: 'upload_image',
                    });
                    rejects();
                    return;
                  }
                  if (!isLt512K) {
                    message.error({
                      content: '文件过大，请上传一个小于512KB的文件',
                      key: 'upload_image',
                    });
                    rejects();
                    return;
                  }
                  resolve(true);
                })
              }
            >
              <Upload
                action="/api/file/upload/singleImage"
                listType="picture-card"
                defaultFileList={fileList}
                // fileList={fileList}
                // onRemove={onRemove}
                onChange={onChange}
                onPreview={handlePreview}
                maxCount={9}
                style={{ width: 200 }}
              >
                {fileList.length >= 9 ? null : (
                  <Button icon={<UploadOutlined />} style={{ width: '106px', height: '106px' }}>
                    <div>
                      <a>点击上传图片</a>
                    </div>
                    <a> ( 375 * 144 )</a>
                  </Button>
                )}
              </Upload>
            </ImgCrop>
            <Modal
              visible={previewVisible}
              title={previewTitle}
              footer={null}
              onCancel={handleCancel}
              width={650}
            >
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </ProForm.Item>
        </ProForm>
      </Modal>
    </div>
  );
};
